<?php

namespace App\Console\Commands;

use App\Http\Controllers\Api\MiniProgramController;
use App\Models\Order;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 下单成功发送小程序模板消息
 * Class SendCashSms
 * @package App\Console\Commands
 */
class SendTemplateMessage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:templateMessage';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '下单成功之后发送小程序模板消息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {
        try {
            $miniprogram_controller = new MiniProgramController();
            $access_token = $miniprogram_controller->getAccessToken();
            if ($access_token) {
                $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
                $client = new Client();
                //查询待发货的订单
                $orders = Order::join('order_products', 'orders.id', '=', 'order_products.order_id')
                    ->join('products','order_products.product_id','=','products.id')
                    ->join('product_skus', 'order_products.sku_id', '=', 'product_skus.id')
                    ->join('users', 'orders.user_id', '=', 'users.id')
                    ->select('orders.id','hexiao_type','products.title as product_title','users.mobile','nickname','orders.openid', 'no', 'cash_money', 'product_skus.title as sku_title')
                    ->where('orders.status', TO_DELIVERY)
                    ->whereNull('template_message_sent_at')
                    ->OrderBy('orders.id','asc')->limit(10)->get();

                if (count($orders) > 0) {
                    foreach ($orders as $order) {
                        $post_data = [
                            'touser'                =>  $order->openid,
                            'template_id'           =>  'DoPbY3Lb_xIhgt7XnpG_EAbgaWnxwmwZ7UFH2hiVxqo',
                            'data'                  =>  [
                                'time1'             =>  ['value' => $order->created_at],
                                'thing2'            =>  ['value' => mb_substr($order->product_title . '--' . $order->sku_title, 0, 20)],
                                'character_string4' =>  ['value' => $order->delivery],
                                'thing13'           =>  ['value' => $order->username],
                                'thing14'           => ['value' => '']
                            ]
                        ];

                        Log::info("post_data：");
                        Log::info(print_r($post_data, 1));

                        $content = $client->request('post', $url,['headers'=>["Content-type: text/html; charset=utf-8"],'json' => $post_data])
                                    ->getBody()->getContents();

                        $content = json_decode($content, 1);

                        Log::info("发货提醒模板消息推送结果：");
                        Log::info(print_r($content, 1));

                        if ($content['errcode'] == 0 || $content['errcode'] == 43101) {
                            //发送成功或者用户拒绝接收
                            Order::where('id', $order->id)->update(['template_message_sent_at' => date('Y-m-d H:i:s', time())]);
                        }
                    }
                }
            }
        } catch (\Exception $exception) {
            Log::info("发送发货提醒模板消息失败：");
            Log::info($exception);

            echo "发送模板消息失败：\n";
        }
    }


}
